<template>
  <div id="app">
    <div class="box">
      <h2 style="text-align: center; color: #409EFF;">账号登录</h2>
      <br />
      <el-form :model="ruleForm"
               :rules="rules"
               ref="ruleForm"
               class="demo-ruleForm">
        <el-form-item label="账号"
                      prop="codeName">
          <el-input v-model="ruleForm.codeName"
                    autocomplete="off"
                    placeholder="字母开头，允许6~10字符，允许字母数字下划线"></el-input>
        </el-form-item>

        <el-form-item label="密码"
                      prop="pass">
          <el-input type="password"
                    show-password
                    v-model="ruleForm.pass"
                    placeholder="6~10总字符长度"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item style="margin: auto; width: 200px;">
          <el-button type="primary"
                     @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    // 添加学生账号的正则
    let validateCode = (rule, value, callback) => {
      // /^[\u4e00-\u9fa5a-zA-Z][\u4e00-\u9fa5a-zA-Z\d]{3,6}$/
      let reg = /^[a-zA-Z][a-zA-Z0-9_]{5,9}$/;
      if (!reg.test(value)) {
        callback(new Error("字母开头，允许6~10字符，允许字母数字下划线"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        // callback();
        let reg = /^.{6,16}$/;
        if (!reg.test(value)) {
          callback(new Error("6~16总字符长度"));
        } else {
          callback();
        }
      }
    };

    return {
      ruleForm: {
        // royalserve
        // A1fy@N*sbcAdi@JM
        codeName: "",
        pass: "",
      },
      rules: {
        codeName: [
          {
            required: false,
            message: "请输入账号",
            trigger: "blur",
          },
          {
            validator: validateCode,
            trigger: "blur",
          },
        ],
        pass: [
          {
            required: false,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            validator: validatePass,
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted () {
    // return this.$cookies.keys();
    // let cookiessss = this.$cookies.keys();
    // console.log(cookiessss);
    // this.$cookies.remove("user");
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let ToLogin = this.axios.create({
            baseURL: "https://albeibei.cn/rm/v1/",
            timeout: 1500,
          });
          // 原型上挂载axios,便于全局使用
          // Vue.prototype.axios = axios
          // 设置axios的返回拦截（还可以设置request拦截，这里暂时用不上）
          ToLogin.interceptors.response.use(
            (response) => {
              return response;
            },
            (error) => {
              if (error.message.includes("timeout")) {
                // 判断请求异常信息中是否含有超时timeout字符串
                console.log("错误回调", error); // alert("网络超时");
                return Promise.reject(error); // reject这个错误信息
              }
              return Promise.reject(error);
            }
          );
          // 登录接口
          ToLogin({
            method: "post",
            url: "login",
            data: {
              username: this.ruleForm.codeName,
              password: this.ruleForm.pass,
            },
          })
            .then(() => {
              this.$message({
                message: "登录成功",
                showClose: true,
                // duration: 0,
                type: "success",
                center: true,
              });
              // cookie 设置
              // $cookies.config(expireTimes[,path[, domain[, secure[, sameSite]]]);
              // default: expireTimes = 1d, path = '/', domain = '', secure = '', sameSite = ''
              // set default config 3天后过期
              this.$cookies.config("3d", "/", "", "", "Lax");
              var user = {
                username: this.ruleForm.codeName,
                password: this.ruleForm.pass,
              };
              this.$cookies.set("user", user);
              // print user name
              console.log(this.$cookies.get("user").username);
              // 页面跳转
              let userId = this.ruleForm.codeName;
              this.$router.push({
                path: "/index",
                query: {
                  id: userId,
                },
              });
            })
            .catch((err) => {
              this.$message({
                message: "失败，请联系管理员",
                showClose: true,
                duration: 0,
                type: "warning",
                center: true,
              });
              console.log("error", err);
            });
        } else {
          this.$message({
            message: "登录失败",
            type: "warning",
            center: true,
          });
          return false;
        }
      });
    },
    // 重置
    resetForm (formName) {
      console.log(this);
      this.$refs[formName].resetFields(); //重置内容
    },
  },
};
</script>

<style>
.box {
  width: 400px;
  margin: auto;
  margin-top: 10%;
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  padding: 50px 100px 100px 100px;
  background-color: #f2f6fc;
}
</style>
